package com.xt.yncu.html;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.xt.base.util.DateUtils;
import com.xt.base.wireless.util.ByteUtil;
import com.xt.yncu.util.Config;
import com.xt.yncu.util.OfficeOther;

/**
 * <br>
 * <br>
 * 
 * <p>
 * <a href=".java.html"><i>查看源文件</i></a>
 * </p>
 * 
 * @author 邵勇
 * @create-date:2011-11-8
 */
public class XmlParseHtml {
	private static Logger log = Logger.getLogger(XmlParseHtml.class);
	private OfficeOther other=new OfficeOther();
	private Config config;
	/* 当前地址 */
	public String httpHost;
	private String fontColor;
	/* 保存附件路径 */
	public List<String> fileList = new ArrayList<String>();
	/* 文件标识 */
	public List<String> fileInfoid = new ArrayList<String>();
	/* 发文唯一ID */
	public String universalid;
	/* 生成公文的HTML名称 */
	public String createHtmlName;
	/* 是否是KJava访问 */
	public boolean isKJava = false;
	public String os ;

	/**
	 * 解析XML 返回:Html字符串
	 * */
	@SuppressWarnings("unchecked")
	public String xmlParse(String xmlString, String funcid) {
		StringBuilder tableHtml = new StringBuilder();
		String s ="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"
				+"<html xmlns=\"http://www.w3.org/1999/xhtml\">"
				+"<head>"
				//+"<meta name='viewport' content='width=device-width, user-scalable=yes' />"
				+"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=yes\" />"
				//+"<meta name='viewport' content='target-densitydpi=high-dpi,width=device-width, initial-scale=1.0, user-scalable=yes' />"
				+"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
				+"<title>内容显示页</title>"
				
				+"<style>"
				+"* {margin:0px;padding:0px;word-wrap:break-word;}"
				+"body {margin:0px auto;font-size:15px;color:#333;line-height:150%;background:url(../img/bg.png);text-align:center;}"
				/*+"div {margin:0px auto;width:318px;}"
				+"table {margin:0px auto;width:320px;text-align:left;}"*/
				+"div {margin:0px auto;width:100%;}"
				+".border {width:480px;}"
				+"table {margin:0px auto;width:100%;text-align:left;}"
				+"div,th,td {min-height:30px;border:1px solid #fff;border-right:1px solid #ccc;border-bottom:1px solid #ccc;}"
				+".title {width:308px;font-size:18px;font-weight:bold;padding:7px 5px;text-align:center;}"
				+"h5 {font-size:15px;}"
				+"div h5 {float:left;width:50%;line-height:30px;vertical-align:middle;color:#777;text-align:center;}"
				+"table th {width:75px;color:#C00;}"
				+"table td {font-weight:bold;padding-left:5px;}"
				+"h3 {width:70px;font-size:15px;padding:5px 0px;color:#C00;}"
				+"h4 {font-weight:normal;color:#333;padding:3px 2px;display:inline-block;}"
				+"td h5 {padding:0px 5px;display:inline-block;}"
				+"td h5 input {margin:2px;padding:0px 5px;width:95px;font-size:15px;line-height:26px;vertical-align:middle;border:1px solid #fff;border-right:1px solid #ccc;border-bottom:1px solid #ccc;text-align:right;background:#e0e0e0 url(../img/s.png) no-repeat 5px 2px;}"
				+"</style>"
				+"<script language='javascript'>"
				+
				//" function test(){alert('调着啦！');}" +
				//"test();" +
				//"window.attachment.js('pb51jpg730837null','abcd');" +
				"function changeStatus(id,sta){alert(id+sta);" +
				"var o = document.getElementById(id);" +
				"if(sta=='download'){o.innerHTML='下载中..';}" +
				"else if(sta=='success'){o.innerHTML='点击查看';}" +
				"else{o.innerHTML='点击下载'}" +
				"}"
				+"</script>"
				+"</head>"
				+"<body>"
				+"<div id='testDiv'>testDiv</div>";
		String head = s;
		if (!isKJava) {
			tableHtml
			.append(s);

		}
		
		try {
			Document document = DocumentHelper.parseText(xmlString);
			Element root = document.getRootElement();
			String seqNumber = "";
			if(root.element("seqnumber")!=null){
				seqNumber = root.element("seqnumber").getTextTrim();
			}
			
			String formType = "";
			if(root.element("formname")!=null){
				formType = root.element("formtype").getTextTrim();
			}
			String formName = "";
			if(root.element("formname")!=null){
				formName = root.element("formname").getTextTrim();
			}
			
			String activetype = "";
			if(root.element("activetype")!=null){
				activetype = root.element("activetype").getTextTrim();
			}
			
			String contentid = "";
			if(root.element("contentid")!=null){
				contentid = root.element("contentid").getText();//.getTextTrim();
			}
			String universalid = root.element("universalid").getTextTrim();
			int contentSize = StringUtils.isEmpty(getNodeString(root,
					"contentsize")) ? 0 : Integer.parseInt(getNodeString(root,
					"contentsize"));

			this.setUniversalid(universalid);
			if (StringUtils.isNotEmpty(contentid)) {
				this.setFileInfoid(contentid);
			}
			this.setFontColor(fontColor(formType));
			
			if(StringUtils.isNotEmpty(formType)){
				tableHtml
					.append("<div class=\"title\">")
					.append(formType).append("</div>");
				}
			
			s = "";
			if(StringUtils.isNotEmpty(seqNumber)){
				s+="<h5>"+seqNumber+"</h5>";
			}
			if(StringUtils.isNotEmpty(formName)){
				s+="<h5>"+formName+"</h5>";
			}
			if(!"".equals(s)){
				s = "<div>"+s+"</div>";
				tableHtml.append(s);
			}
			
			/*公文以外的模块的标题*/
			if(root.element("Title")!=null){
				s = root.element("Title").getTextTrim();
				tableHtml
				.append("<div class=\"title\">")
				.append(s)
				.append("</div>");
			}
			if(root.element("title")!=null){
				s = root.element("title").getTextTrim();
				tableHtml
				.append("<div class=\"title\">")
				.append(s)
				.append("</div>");
			}
			
			tableHtml.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");
			
			/* 签发解析 */
			List<Object> prefixList = document
					.selectNodes("//prefix/list/value");
			tableHtml.append(parsePrefix(prefixList));
			/* 签发人解析 */
			List<Object> listElement = root.selectNodes("comment/list/value");
			for (int i = 0; i < listElement.size(); i++) {
				Element row = (Element) listElement.get(i);
				List<Object> nextList = row.selectNodes("list");
				if (nextList.size() > 0) {
					tableHtml.append(moreInStruction(row, activetype, funcid));
				} else {
					tableHtml
							.append(otherInstructions(row, activetype, funcid));
				}
			}
			/* 解析尾信息 */
			List<Object> listSuffix = root.selectNodes("suffix/list/value");
			if (listSuffix.size() > 0) {
				tableHtml.append(parseSuffix(listSuffix));
			}
			
			s = "";
			
			
			//会议通知表单
			if(root.element("form")!=null){
				s = root.element("form").getTextTrim();
				tableHtml
				.append("<tr><th colspan=\"2\">")
				.append(s)
				.append("</th></tr>");
			}
			
			if(root.element("date")!=null){
				s = root.element("date").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">日期</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			if(root.element("time")!=null){
				s = root.element("time").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">日期</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			if(root.element("author")!=null){
				s = root.element("author").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">发布人</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			if(root.element("auth")!=null){
				s = root.element("auth").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">发布人</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			
			//会议通知
			if(root.element("Meet_Dep")!=null){
				s = root.element("Meet_Dep").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">筹备单位</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			if(root.element("Meet_date")!=null){
				s = root.element("Meet_date").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">会议日期</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			if(root.element("Meet_Time")!=null){
				s = root.element("Meet_Time").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">具体时间</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			if(root.element("Meet_Site")!=null){
				s = root.element("Meet_Site").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">会议地点</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			if(root.element("Meet_notify_Time")!=null){
				s = root.element("Meet_notify_Time").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">通知时间</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			if(root.element("Meet_Content")!=null){
				s = root.element("Meet_Content").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">会议内容</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			if(root.element("Remark")!=null){
				s = root.element("Remark").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">备注</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			if(root.element("CallerName")!=null){
				s = root.element("CallerName").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">发起人</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			if(root.element("whoOnInvitationName")!=null){
				s = root.element("whoOnInvitationName").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">参加人</th><td>")
				.append(s)
				.append("</td></tr>");
			}
			//带有正文文本内容 
			s = "";
			if(root.element("content")!=null){
				s = root.element("content").getTextTrim();
				tableHtml
				.append("<tr><th width=\"20%\">正文</th><td>")
				.append(s)
				.append("</td></tr>");
			}else{
			/* 正文 */
			tableHtml
					.append("<tr><th>正文</th><td><h4>");
			if (isKJava) {
				tableHtml.append("[请用电脑查看]");
			} else {
				if (contentSize > getAttSize()) {
					tableHtml.append("[文件过大，请用电脑查看]");
				} else {
					String fileMtime="";
					if (root.element("fileMtime")!=null) {
						fileMtime=root.element("fileMtime").getTextTrim();
					}
					tableHtml.append(attachmentHtml(contentid,fileMtime, 0,getAttSize(),""));
				}
			}
			tableHtml.append("</h4></td></tr>");
			}
			/* 附件解析 */
			List<Object> listAttachment = root
					.selectNodes("attachment/list/value");
			if (listAttachment.size() > 0) {
				tableHtml
						.append("<tr><td colspan=\"2\"><h3>附　　件</h3>");
				tableHtml.append(parseAttachment(listAttachment))
				.append("</td></tr>");
			}
			
			if("F001".equals(funcid)){
				tableHtml = new StringBuilder();
				tableHtml.append(head);
				if(root.element("Title")!=null){
					s = root.element("Title").getTextTrim();
					tableHtml
					.append("<div class=\"title\">")
					.append(s).append("</div>");
				}
				tableHtml.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");
				if(root.element("formtype")!=null){
					s = root.element("formtype").getTextTrim();
					tableHtml
					.append("<tr><th width=\"20%\">会议室</th><td>")
					.append(s)
					.append("</td></tr>");
				}
				if(root.element("StartTime")!=null){
					s = root.element("StartTime").getTextTrim();
					tableHtml
					.append("<tr><th width=\"20%\">开始时间</th><td>")
					.append(s)
					.append("</td></tr>");
				}
				if(root.element("EndTime")!=null){
					s = root.element("EndTime").getTextTrim();
					tableHtml
					.append("<tr><th width=\"20%\">结束时间</th><td>")
					.append(s)
					.append("</td></tr>");
				}
				if(root.element("time")!=null){
					s = root.element("time").getTextTrim();
					tableHtml
					.append("<tr><th width=\"20%\">申请时间</th><td>")
					.append(s)
					.append("</td></tr>");
				}
				if(root.element("auth")!=null){
					s = root.element("auth").getTextTrim();
					tableHtml
					.append("<tr><th width=\"20%\">申请人</th><td>")
					.append(s)
					.append("</td></tr>");
				}
				if(root.element("content")!=null){
					s = root.element("content").getTextTrim();
					tableHtml
					.append("<tr><th width=\"20%\">申请部门</th><td>")
					.append(s)
					.append("</td></tr>");
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		tableHtml.append("</table>");
		if (!isKJava) {
			tableHtml.append("</body></html>");
		}
		// System.out.println(tableHtml.toString());
		return String.valueOf(tableHtml) == null ? "" : String
				.valueOf(tableHtml);
	}

	/** 签发XML解析 */
	@SuppressWarnings("unchecked")
	private String parsePrefix(List<Object> prefixList) {
		StringBuilder endTable = new StringBuilder();
		String dateFormat = "";
		for (int i = 0; i < prefixList.size(); i++) {
			Element row = (Element) prefixList.get(i);
			List<Object> value = row.elements();
			if (hasRootElement(row)) {
				if (nodeIsExit(row, "itemtype")) {
					if (getNodeString(row, "itemtype").equals("date")) {
						String dateStr = getNodeString(row, "itemvalue");
						if (StringUtils.isNotEmpty(dateStr)) {
							long date = Long.valueOf(dateStr);
							Date parseDate = new Date(date);
							dateFormat = DateUtils.format(parseDate,
									"yyyy-MM-dd");
						}
						endTable.append("<tr><th>");
						//endTable.append(getFontColor()).append("\">");
						endTable.append(getNodeString(row, "itemname"));
						endTable.append("</th>");
						endTable.append("<td>");
						endTable
								.append("<input name=\"itemcode\" type=\"hidden\" value=\"");
						endTable.append(getNodeString(row, "itemcode"));
						endTable.append("\" id=\"itemcode\"/>");
						endTable.append(dateFormat);
						endTable.append("</td>");
						endTable.append("</tr>");
					}
				} else {
					/*endTable.append("<tr bgcolor=\"#ffffff\">");
					endTable.append("<td width=\"80\">");
					endTable.append("<font color=\"");
					endTable.append(getFontColor()).append("\">");*/
					endTable.append("<tr><th>");
					endTable.append(getNodeString(row, "itemname"));
					/*endTable.append("</font></td>");
					endTable.append("<td width=\"230\">");*/
					endTable.append("</th>");
					endTable.append("<td>");
					endTable
							.append("<input name=\"itemcode\" type=\"hidden\" value=\"");
					endTable.append(getNodeString(row, "itemcode"));
					endTable.append("\" id=\"itemcode\"/>");
					endTable.append(getNodeString(row, "itemvalue"));
					endTable.append("</td>");
					endTable.append("</tr>");
				}
			}
		}
		return String.valueOf(endTable) == null ? "" : String.valueOf(endTable);
	}

	/** 多人会签Html处理 */
	@SuppressWarnings("unchecked")
	private String moreInStruction(Element row, String activetype, String funcid) {
		StringBuilder inBuilder = new StringBuilder();
		StringBuilder endTable = new StringBuilder();
		String dateFormat = "";
	
		List<Object> value = row.elements();
		if (hasRootElement(row)) {
			String itemname = getNodeString(row, "itemname");
			String itemcode = getNodeString(row, "itemcode");
			/*inBuilder.append("<tr bgcolor=\"#ffffff\">");
			inBuilder.append("<td>");
			inBuilder.append("<font color=\"");
			inBuilder.append(getFontColor()).append("\">");
			inBuilder.append(itemname);
			inBuilder.append("</font></td>");
			inBuilder.append("<td>");*/
			inBuilder.append("<tr><th>");
			inBuilder.append(itemname);
			inBuilder.append("</th><td>");
			inBuilder
					.append("<input name=\"itemcode\" type=\"hidden\" value=\"");
			inBuilder.append(itemcode);
			inBuilder.append("\" id=\"itemcode\"/>");
			List<Object> endList = row.selectNodes("list/value");
			if (endList.size() > 0) {
				//endTable.append("<table width=\"80%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
				for (int i = 0; i < endList.size(); i++) {
					Element endValue = (Element) endList.get(i);
				
					List<Object> endList2 = endValue.elements();
					try {
						String dateStr = getNodeString(endValue, "date");
						if (StringUtils.isNotEmpty(dateStr)) {
							long date = Long.valueOf(dateStr);
							Date parseDate = new Date(date);
							dateFormat = DateUtils.format(parseDate,
									"yyyy-MM-dd");
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					//endTable.append("<tr><td align=\"left\">");
					//endTable.append("<font size=\"+1\">");
					endTable.append(getNodeString(endValue, "content"))
					.append("<br>");
					//.append("</font></td></tr>");
					//endTable.append("<tr><td align=\"right\">");
					endTable.append(getNodeString(endValue, "orgname")).append(
							"&nbsp;&nbsp;");
					endTable.append(getNodeString(endValue, "approver"))
							.append("&nbsp;&nbsp;");
					endTable.append(dateFormat);
					//endTable.append("</td></tr>");
				}
				//endTable.append("</table>");
			}
			if (activetype.equals(itemcode)) {
				endTable.append("<br><font color=\"#930\">*");
				endTable.append(documentType(funcid));
				endTable.append("*</font>");
			}
			inBuilder.append(String.valueOf(endTable));
			inBuilder.append("</td></tr>");
		}
		// System.out.println(String.valueOf(endTable));
		return String.valueOf(inBuilder) == null ? "" : String
				.valueOf(inBuilder);
	}

	/** 其它批示Html处理 */
	@SuppressWarnings( { "unused", "unchecked" })
	private String otherInstructions(Element row, String activetype,
			String funcid) {
		StringBuilder endTable = new StringBuilder();
		String dateFormat = "";
		List<Object> value = row.elements();
		if (hasRootElement(row)) {
			try {
				String dateStr = getNodeString(row, "date");
				if (StringUtils.isNotEmpty(dateStr)) {
					long date1 = Long.valueOf(dateStr);
					Date parseDate1 = new Date(date1);
					dateFormat = DateUtils.format(parseDate1, "yyyy-MM-dd");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			String itemname = getNodeString(row, "itemname");
			String itemcode = getNodeString(row, "itemcode");
			String approver = getNodeString(row, "approver");
			String orgname = getNodeString(row, "orgname");
			String content = getNodeString(row, "content");
			endTable.append("<tr ><th>");
			//endTable.append("<font color=\"");
			//endTable.append(getFontColor()).append("\">");
			endTable.append(itemname);
			endTable.append("</th><td>");
			endTable
					.append("<input name=\"itemcode\" type=\"hidden\" value=\"");
			endTable.append(itemcode);
			endTable.append("\" id=\"itemcode\"/>");
			//endTable.append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\"><tr>");
			//endTable.append("<td align=\"left\">");
			//endTable.append("<font size=\"+1\">");
			endTable.append(content).append("<br>");
			//endTable.append("</font>");
			//endTable.append("</td><tr><td align=\"right\">");
			endTable.append(orgname).append("&nbsp;&nbsp;&nbsp;").append(
					approver).append("&nbsp;&nbsp;&nbsp;").append(dateFormat);
			//endTable.append("</td></tr></table>");
			if (activetype.equals(itemcode)) {
				/*endTable
						.append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
				endTable.append("<tr><td><font color=\"#0000FF\">&lt;");*/
				endTable.append("<br><font color=\"#930\">*");
				endTable.append(documentType(funcid));
				endTable.append("*</font>");//</td></tr>
				//endTable.append("</table>");
			}
			endTable.append("</td></tr>");
		}
		return String.valueOf(endTable) == null ? "" : String.valueOf(endTable);
	}

	/** 返回公文类型 */
	private String documentType(String funcid) {
		if ("B001".equals(funcid) || "C001".equals(funcid)
				|| "D001".equals(funcid) || "F001".equals(funcid)) {
			return "点击顶部按钮批示";
		}
		if ("B002".equals(funcid)) {
			return "点击顶部按钮已阅";
		}
		return "此节点等待审批";
	}

	/**
	 * 附件XMl解析
	 * */
	@SuppressWarnings("unchecked")
	private String parseAttachment(List<Object> listAttachment) {
		StringBuilder endTable = new StringBuilder();
		for (int i = 0; i < listAttachment.size(); i++) {
			Element row = (Element) listAttachment.get(i);
			if (hasRootElement(row)) {
			
				List<Object> listAtt = row.elements();
				
				String fileName = "";
				if (nodeIsExit(row, "att_zh_name")) {
					fileName = row.element("att_zh_name").getText();
				}
				//String fileName = getNodeString(row, "att_zh_name");
				
				String fileInfoid = "";//
				if (nodeIsExit(row, "att_infoid")) {
					fileInfoid = row.element("att_infoid").getText();
				}
				//getNodeString(row, "att_infoid");
				String fileMtime=getNodeString(row, "fileMtime");
				int attSize = StringUtils
						.isEmpty(getNodeString(row, "attsize")) ? 0 : Integer
						.parseInt(getNodeString(row, "attsize"));
				if (!fileName.equals("")) {
					endTable
							.append("<h4>");
					if (fileParse(fileName)) {
						endTable.append("<font size=\"+1\">");
						endTable.append(fileName);
						endTable.append("</font>");
						if (isKJava) {
							endTable.append("[请用电脑查看]");
						}else {
							if (attSize > getAttSize()) {
								endTable.append("[文件过大，请用电脑查看]");
							} else {
								endTable.append(attachmentHtml(fileName,fileMtime, i + 10,attSize,""));
								this.setFileInfoid(fileInfoid);
							}
						}
					} else {
						if (isKJava) {
							endTable.append(fileName).append("[请用电脑查看]");
						}else {
							endTable.append(fileName).append("[不支持]");
						}
					}
					endTable.append("</h4><br>");
				}
			}
		}
		return String.valueOf(endTable) == null ? "" : String.valueOf(endTable);
	}

	/** 解析XML尾信息 */
	@SuppressWarnings("unchecked")
	private String parseSuffix(List<Object> listSuffix) {
		StringBuilder endTable = new StringBuilder();
		String dateFormat = "";
		for (int i = 0; i < listSuffix.size(); i++) {
			Element row = (Element) listSuffix.get(i);
			if (hasRootElement(row)) {
			
				List<Object> listSuf = row.elements();
				if (nodeIsExit(row, "itemtype")) {
					if (getNodeString(row, "itemtype").equals("date")) {
						String endDate = getNodeString(row, "itemvalue");
						if (endDate != null&&!endDate.equals("")&& endDate.indexOf("-")<0) {
							long date1 = Long.valueOf(endDate);
							Date parseDate1 = new Date(date1);
							dateFormat = DateUtils.format(parseDate1,
									"yyyy-MM-dd");
						}else{
							dateFormat = endDate;
						}
						//endTable.append("<tr bgcolor=\"#ffffff\"><td>");
						//endTable.append("<font color=\"");
						//endTable.append(getFontColor()).append("\">");
						endTable.append("<tr><th>");
						endTable.append(getNodeString(row, "itemname"));
						endTable.append("</th>");
						endTable.append("<td>");
						endTable
								.append("<input name=\"itemcode\" type=\"hidden\" value=\"");
						endTable.append(getNodeString(row, "itemcode"));
						endTable.append("\" id=\"itemcode\"/>");
						endTable.append(dateFormat);
						endTable.append("</td></tr>");
					}
				} else {
					//endTable.append("<tr bgcolor=\"#ffffff\"><td>");
					//endTable.append("<font color=\"");
					//endTable.append(getFontColor()).append("\">");
					endTable.append("<tr><th>");
					endTable.append(getNodeString(row, "itemname"));
					endTable.append("</th>");
					endTable.append("<td>");
					endTable
							.append("<input name=\"itemcode\" type=\"hidden\" value=\"");
					endTable.append(getNodeString(row, "itemcode"));
					endTable.append("\" id=\"itemcode\"/>");
					endTable.append(getNodeString(row, "itemvalue"));
					endTable.append("</td></tr>");
				}
			}
		}
		return String.valueOf(endTable) == null ? "" : String.valueOf(endTable);
	}
	private String attachmentHtml(String fileName,String fileMtime, int i,int attSize,String attUrl) {
		
		if(attUrl==null||"".equals(attUrl)){
			attUrl="http://192.168.1.102:8080/kmzy/VBS12323121_2011_xx.doc";
		}
		
		String s = cn2FirstSpell(fileName)+attSize+fileMtime+"."+other.getExtension(fileName);
		StringBuilder sb = new StringBuilder();
		sb.append("")
		.append("<a href='http://www.attachView.com?attName=").append(s)
		.append("&attSize=").append(attSize)
		.append("&attUrl=").append(attUrl==null?"":ByteUtil.binaryToHexString(attUrl.getBytes()))
		.append("' target='_top'><h5 name='attachNameH5' id='").append(s).append("'>点击查看</h5></a>")
		.append("");
		return sb.toString();
	}
	/** 附件HTML */
	/*private String attachmentHtml(String fileName,String fileMtime, int i,int attSize) {
		StringBuilder html = new StringBuilder();
		String fileExtension = other.getExtension(fileName);
		//String newFileName = other.createSaveName() + (i * 10);
		String newFileName =other.StringFilter(other.cn2Spell(fileName)+"_"+fileMtime + (i * 10));
		if (fileParse(fileExtension)) {
			return "";
		}
		if (StringUtils.isEmpty(fileExtension)) {
			return "";
		}
		StringBuilder allFileName = new StringBuilder();
		allFileName.append(newFileName).append(".").append(fileExtension);
		html.append("&nbsp;&nbsp;");
		// html.append("<span id=\"").append(newFileName).append("\"></span>");
		html.append("<iframe src=\"");
		html.append(config.getNetworkAddress());
		html.append("/attachment/attachmentAction!fileIsExit.action");
		html.append("?fileName=").append(String.valueOf(allFileName));
		html.append("&htmlId=").append(newFileName);
		html
				.append("\" frameborder=\"0\" scrolling=\"no\" width=\"130\" height=\"35\">");
		html.append("</iframe>");
		this.setFileList(String.valueOf(allFileName));
		return String.valueOf(html);
	}*/
	
	/** 附件HTML ServletActionContext.getRequest()*/
	@SuppressWarnings("unchecked")
	/*private String attachmentHtml2(String fileName, int i,int attSize) {
		StringBuilder html = new StringBuilder();
		StringBuilder allFileName = new StringBuilder();
		String newFileName = null;
		
		从application中取出已经解析过的附件
		ServletContext sc = ServletActionContext.getServletContext();
		Map<String,Object> map = (Map<String,Object>)sc.getAttribute("attachment");
		String s = map==null?null:String.valueOf(map.get(fileName+attSize));
		
		if(StringUtils.isNotEmpty(s)){
			newFileName = s.split(".")[1];
			allFileName.append(s);
		}else{
			String fileExtension = other.getExtension(fileName);
			newFileName = other.createSaveName() + (i * 10);
			if (fileParse(fileExtension)) {
				return "";
			}
			if (StringUtils.isEmpty(fileExtension)) {
				return "";
			}
			allFileName.append(newFileName).append(".").append(fileExtension);
			this.setFileList(String.valueOf(allFileName));
		}
		
		html.append("&nbsp;&nbsp;");
		// html.append("<span id=\"").append(newFileName).append("\"></span>");
		html.append("<iframe src=\"");
		html.append(config.getNetworkAddress());
		html.append("/attachment/attachmentAction!fileIsExit.action");
		html.append("?fileName=").append(String.valueOf(allFileName));
		html.append("&htmlId=").append(newFileName);
		html
				.append("\" frameborder=\"0\" scrolling=\"no\" width=\"130\" height=\"35\">");
		html.append("</iframe>");
		
		return String.valueOf(html);
	}*/

	/** 移出XML相关项,返回一个新的Xml字符串 */
	private String removeXMlChild(String xmlString) {
		try {
			Document document = DocumentHelper.parseText(xmlString);
			Element root = document.getRootElement();
			Element seqNumber = root.element("seqnumber");
			Element formType = root.element("formtype");
			Element formName = root.element("formname");
			Element comment = root.element("comment");
			Element prefix = root.element("prefix");
			Element attachment = root.element("attachment");
			Element suffix = root.element("suffix");
			/* 移除表单标识 */
			root.remove(seqNumber);
			/* 移除表单发文类型 */
			root.remove(formType);
			/* 移除表单名称 */
			root.remove(formName);
			/* 移除批示信息 */
			root.remove(comment);
			/* 移除批示列表 */
			root.remove(prefix);
			/* 移除附件 */
			root.remove(attachment);
			/* 移除后缀 */
			root.remove(suffix);
			
			/* 移除标题 */
			root.remove(root.element("title"));
			root.remove(root.element("Title"));
			
			/* 移除日期 */
			root.remove(root.element("date"));
			root.remove(root.element("time"));
			
			/* 移除发布人呢*/
			root.remove(root.element("author"));
			root.remove(root.element("auth"));
			
			/* 移除会议通知 */
			root.remove(root.element("form"));
			root.remove(root.element("Meet_Dep"));
			root.remove(root.element("Meet_date"));
			root.remove(root.element("Meet_Site"));
			root.remove(root.element("Meet_Time"));
			root.remove(root.element("Meet_notify_Time"));
			root.remove(root.element("Meet_Content"));
			root.remove(root.element("Remark"));
			root.remove(root.element("CallerName"));
			root.remove(root.element("whoOnInvitationName"));
			
			/* 移除正文文本 */
			root.remove(root.element("content"));
			
			root.addElement("htmlContent");
			Element htmlContent = root.element("htmlContent");
			htmlContent.setText("<![CDATA[#kmxt#]]>");
			
//			root.addElement("editable");
//			Element editable=root.element("editable");
//			editable.setText("no");
			
			StringBuilder newXml = new StringBuilder();
			newXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			newXml.append(root.asXML());
			return String.valueOf(newXml);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/** 生成新XML供手机端使用 */
	public String mobileNewXml(String xmlString, String funid) {
		StringBuilder savePath;
		/*StringBuilder imagePath;*/
		String htmlName = other.createSaveName();
		if (isXMLString(xmlString)) {
			return errorXmlString(xmlString);
		} else if (webServiceErr(xmlString)) {
			return xmlString;
		} /*else if (isKJava) {
			String htmlString = xmlParse(xmlString, funid);
			savePath=new StringBuilder();
			imagePath=new StringBuilder();
			
			savePath = new StringBuilder();
			savePath.append(other.createFolder(config.getProcessFolder()))
					.append("\\");
			savePath.append(htmlName);
			imagePath.append(savePath.toString()).append(".png");
			savePath.append(".html");
			System.out.println(imagePath.toString());
			other.htmlToImage(htmlString, imagePath.toString());
			// 生成程批件Html
			other.writeFile(wapHtml(htmlName+".png"), savePath.toString());
			String newXmlString = removeXMlChild(xmlString);
			savePath = new StringBuilder();
			savePath.append(config.getNetworkAddress()).append("/").append(config.getProcessFolder()).append("/");
			savePath.append(htmlName).append(".html");
			return newXmlString.replace("#kmxt#", savePath.toString()).replace(
					"&lt;", "<").replace("&gt;", ">");
		}*/else {
			String htmlString = xmlParse(xmlString, funid);
			savePath = new StringBuilder();
			savePath.append(other.createFolder(config.getProcessFolder()))
					.append("\\");
			savePath.append(htmlName);
			savePath.append(".html");
			setCreateHtmlName(htmlName);
			String newXmlString = removeXMlChild(xmlString);
			// 生成程批件Html
			other.writeFile(htmlString, savePath.toString());
			savePath = new StringBuilder();
			savePath.append(config.getNetworkAddress());
			savePath.append("/iframe.jsp?fileName=");
			savePath.append(htmlName);
			savePath.append("&folder=").append(config.getProcessFolder())
			.append("&os=").append(os);
			/*StringBuilder sb = new StringBuilder();
			sb.append("<div name='attachNameDiv'>正文</div>");*/
			return newXmlString.replace("#kmxt#", savePath.toString()).replace(
					"&lt;", "<").replace("&gt;", ">");
		}
	}

	/** 是否是XML文件 */
	private boolean isXMLString(String xmlString) {
		String xmlTop = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
				.toLowerCase();
		xmlString = xmlString.toLowerCase();
		if (xmlString.indexOf(xmlTop) < 0) {
			return true;
		}
		return false;
	}

	/** 不是XML返回值 */
	private String errorXmlString(String xmlString) {
		StringBuilder xmlBuilder = new StringBuilder();
		xmlBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		xmlBuilder.append("<mobile>");
		xmlBuilder.append("<exception><![CDATA[WebService异常,异常信息为:").append(
				xmlString).append("]]></exception>");
		xmlBuilder.append("</mobile>");
		return String.valueOf(xmlBuilder);
	}

	/** 判断返回信息是否异常 */
	@SuppressWarnings("unused")
	private boolean webServiceErr(String xmlString) {
		boolean bool = false;
		try {
			Document document = DocumentHelper.parseText(xmlString);
			Element root = document.getRootElement();
			try {
				String exception = root.element("exception").getTextTrim();
				bool = true;
			} catch (Exception e) {
				bool = false;
			}

		} catch (DocumentException e) {
			e.printStackTrace();
			bool = true;
		}
		return bool;
	}

	/**
	 * 读取文件
	 * */
	private String openFile(String filePath) {
		StringBuilder fileContent = new StringBuilder();
		try {
			File f = new File(filePath);
			InputStreamReader fileReader = new InputStreamReader(
					new FileInputStream(f), "UTF-8");
			BufferedReader reader = new BufferedReader(fileReader);
			String line = "";
			while ((line = reader.readLine()) != null) {
				fileContent.append(line);
			}
			reader.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return String.valueOf(fileContent);
	}

	/**
	 * 文件是否能解析
	 * */
	private boolean fileParse(String fileName) {
		String ext = "|" + getExtension(fileName) + "|";
		if (config.getFileExtension().indexOf(ext) >= 0) {
			return true;
		}
		return false;
	}

	/** 判断是否有下层结点 */
	@SuppressWarnings("unchecked")
	private boolean hasRootElement(Element root) {
		boolean flag = false;
		List<Object> list = root.elements();
		for (int i = 0; i < list.size(); i++) {
			String elementStr = ((Element) list.get(i)).getTextTrim();
			if (StringUtils.isNotEmpty(elementStr)) {
				flag = true;
			}
		}
		return flag;
	}

	/* 获取文件扩展名 */
	private String getExtension(String fileName) {
		if ((fileName != null) && (fileName.length() > 0)) {
			int i = fileName.lastIndexOf('.');
			if ((i > -1) && (i < (fileName.length() - 1))) {
				return fileName.substring(i + 1).toLowerCase();
			}
		}
		return null;
	}

	/* 取得文件英文件 */
	@SuppressWarnings("unused")
	private String getFileSpellName(String filePath) {
		Date nowTime = new Date();
		return cn2FirstSpell(getFileName(filePath, 1))
				+ DateUtils.format(nowTime, "yyyyMM");
	}

	/* 取得文件名 */
	private String getFileName(String filePath, int getType) {
		File file = new File(filePath);
		String fileName = file.getName();
		try {
			if (getType == 1) {
				fileName = fileName.substring(0, fileName.indexOf("."));
				return fileName;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;
	}

	/* 判断是否存在"发文"这个关键字 */
	private String fontColor(String formname) {
		if (formname.indexOf("发文") >= 0) {
			return "#FF0000";
		}
		return "#000000";
	}

	/* 取得中文首字母 */
	private String cn2FirstSpell(String chinese) {
		StringBuilder pybf = new StringBuilder();
		char[] arr = chinese.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] > 128) {
				try {
					String[] _t = PinyinHelper.toHanyuPinyinStringArray(arr[i],
							defaultFormat);
					if (_t != null) {
						pybf.append(_t[0].charAt(0));
					}
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			} else {
				pybf.append(arr[i]);
			}
		}
		return pybf.toString().replaceAll("\\W", "").trim().toLowerCase();
	}

	/**
	 * 查找节点是否存在
	 * */
	@SuppressWarnings("unchecked")
	private boolean nodeIsExit(Element node, String nodeName) {
		List<Object> nodeList = node.selectNodes(nodeName);
		if (nodeList.size() > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 取得节点值
	 * */
	private String getNodeString(Element node, String nodeName) {
		if (nodeIsExit(node, nodeName)) {
			return node.element(nodeName).getTextTrim();
		}
		return null;
	}
	/**
	 * WAP版HTML内容
	 * */
	private String wapHtml(String imageName){
		StringBuilder htmlBuilder=new StringBuilder();
		htmlBuilder.append("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\">");
		htmlBuilder.append("<wml>");
		htmlBuilder.append("<card id=\"index\"><img src=\"").append(imageName).append("\"/>");
		htmlBuilder.append("</card></wml>");
		return htmlBuilder.toString();
	}
	
	public String getFontColor() {
		return fontColor;
	}

	public void setFontColor(String fontColor) {
		this.fontColor = fontColor;
	}

	public String getHttpHost() {
		return httpHost;
	}

	public void setHttpHost(String httpHost) {
		this.httpHost = httpHost;
	}

	public List<String> getFileList() {
		return fileList;
	}

	public void setFileList(String fileName) {
		// StringBuilder file = new StringBuilder();
		// file.append(other.getCurrentPath());
		// file.append(other.createFolder(config.downloadPath)).append("/")
		// .append(fileName);
		this.fileList.add(fileName);
	}

	public List<String> getFileInfoid() {
		return fileInfoid;
	}

	public void setFileInfoid(String fileName) {
		this.fileInfoid.add(fileName);
		log.info("ppppppppppppppppp");
		log.info(fileInfoid);
		log.info("ppppppppppppppppp");
	}

	public String getUniversalid() {
		return universalid;
	}

	public void setUniversalid(String universalid) {
		this.universalid = universalid;
	}

	public Config getConfig() {
		return config;
	}

	public void setConfig(Config config) {
		this.config = config;
	}

	public String getCreateHtmlName() {
		return createHtmlName;
	}

	public void setCreateHtmlName(String createHtmlName) {
		this.createHtmlName = createHtmlName;
	}

	private int getAttSize() {
		return config.getAttSize() * 1024 * 1024;
	}

	public boolean isKJava() {
		return isKJava;
	}

	public void setKJava(boolean isKJava) {
		this.isKJava = isKJava;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		XmlParseHtml xml = new XmlParseHtml();
		String xmlString = xml
				.openFile("E:\\Work\\YnCuService_D\\app_show_2.xml");
		//是否是KJava手机访问
		xml.setKJava(true);
//		System.out.println(xml.xmlParse(xmlString, "B001"));
		//System.out.println(xml.mobileNewXml(xmlString, "B001"));
		// List<String> path=xml.getFileList();
		// List<String> info=xml.getFileInfoid();
		// String
		// xmlPath=xml.openFile("E:\\Work\\YnCuService\\WebRoot\\xml\\attachment_1.xml");
		// Map<String,Object> map = MobileActionUtil.parseRequestXml(xmlPath);
		// FileDown fileDown=new FileDown(path, info, xml.getUniversalid(),
		// map,);
		// fileDown.downFileTreadCreate();
		// System.out.println(xml.mobileNewXml(xmlString));
		// String tString = xml.errorXmlString("asdfasdf");
		// System.out.println(tString);
	}

	public String getOs() {
		return os;
	}

	public void setOs(String os) {
		this.os = os;
	}
}
